package cn.risebd.wechat.wechat.controller;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;

import com.alibaba.fastjson.JSON;

import cn.risebd.common.cache.RedisCache;
import cn.risebd.common.security.SignatureUtil;
import cn.risebd.wechat.wechat.support.WechatSupport;

@Controller
@RequestMapping("msg")
public class MsgController {

	private static final Logger logger = LoggerFactory.getLogger(MsgController.class);
	@Autowired
	private WechatSupport wechatSupport;

	@Autowired
	private RedisCache redisCache;
	private final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

	@RequestMapping
	@ResponseBody
	public void root(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request,
			HttpServletResponse response) {
		// 处理微信的消息
		if (!SignatureUtil.checkSignature(wechatSupport.getToken(), signature, timestamp, nonce)) {
			logger.error("存在异常的请求，该次请求的url:{}/{}", request.getRequestURL(), request.getQueryString());
			return;
		}
		try (PrintWriter writer = response.getWriter();) {
			String method = request.getMethod();
			if ("GET".equals(method)) {
				logger.info("微信首次校验的请求,signature={},timestamp={},nonce={},echostr={}", signature, timestamp, nonce,
						echostr);
				writer.print(echostr);
			} else if ("POST".equals(method)) {
				Map<String, String> data = parseRequestXML(request.getInputStream());
				String content = JSON.toJSONString(data);
				// redisCache.push(BaseInFo.WEIXIN_QUEUE_NAME, content);
				logger.info("微信推送过来的消息：content = {}", content);
				writer.print("");
			}
			writer.flush();
		} catch (Exception e) {
			logger.error("处理微信推送过来的消息时，出现异常", e);
		}

	}

	@RequestMapping("index")
	public void index() {
		System.out.println(wechatSupport.getAccessToken());
		System.out.println(wechatSupport.getJSApiTicket());
	}

	private Map<String, String> parseRequestXML(InputStream is) throws Exception {
		Map<String, String> data = new HashMap<String, String>();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(is);
		Element root = doc.getDocumentElement();
		for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
			if (!(node instanceof Element)) {
				continue;
			}
			Element child = (Element) node;
			Node contentNode = child.getFirstChild();
			if (contentNode instanceof Text) {
				Text text = (Text) contentNode;
				data.put(child.getNodeName(), text.getTextContent());
			}
		}
		return data;
	}
}
